package com.cyys.modules.core.shiro.token;

import com.cyys.common.ql.AR;
import com.cyys.common.utils.MD5Util;
import com.cyys.modules.core.shiro.token.manage.TokenManager;
import com.cyys.modules.system.model.user.User;
import com.cyys.modules.system.service.user.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;

/**
 * 
 * shiro 认证 + 授权 重写
 * 
 * @author LC
 * 
 */
public class UserRealm extends AuthorizingRealm {

	@Resource
	UserService userService;
	public UserRealm() {
		super();
	}

	// 设置自定义的MD5加密匹配
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
		HashedCredentialsMatcher tmp = new HashedCredentialsMatcher("MD5");
		tmp.setStoredCredentialsHexEncoded(true);
		super.setCredentialsMatcher(tmp);
	}

	/**
	 * 认证信息，主要针对用户登录，
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		ShiroToken token = (ShiroToken) authcToken;
		AR<User> ar = null;
		User user;
		try {
			ar = userService.shiroLogin(token.getUsername(), token.getPwd(), token.getLoginType());
		}  catch (Exception e) {
			e.printStackTrace();
		}
		if (ar.getCode() != 0) {
			throw new AccountException(ar.getMsg());
		} else {
			user = ar.getData();
		}
		if("2".equals(token.getLoginType())){//验证码登录
			return new SimpleAuthenticationInfo(user, MD5Util.calcMD5(token.getPwd()), token.getUsername());
		}
		return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
	}
	
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		User user = TokenManager.getToken();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(user.getPermissions());
		return info;
	}

	@SuppressWarnings("unused")
	private void setSession(Object key, Object value) {
		Subject currentUser = SecurityUtils.getSubject();
		if (null != currentUser) {
			Session session = currentUser.getSession();
			if (null != session) {
				session.setAttribute(key, value);
			}
		}
	}
}
